package cn.yy.cloudpay.scan;

import java.util.concurrent.TimeUnit;

import com.newland.mtype.ModuleType;
import com.newland.mtype.module.common.light.IndicatorLight;
import com.newland.mtype.module.common.light.LightType;
import com.newland.mtype.module.common.scanner.BarcodeScanner;
import com.newland.mtype.module.common.scanner.ScannerListener;

import cn.yy.cloudpay.R;
import cn.yy.cloudpay.activity.BaseActivity;
import cn.yy.cloudpay.application.CloudPayApplication;
import cn.yy.cloudpay.listener.ITitlebarClickListener;
import cn.yy.cloudpay.ui.ClearEditText;
import cn.yy.cloudpay.util.Constant;
import cn.yy.cloudpay.util.CountDownTimer;
import cn.yy.cloudpay.view.TitlebarLayout;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.AssetFileDescriptor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.os.Bundle;
import android.os.Vibrator;
import android.text.Html;
import android.text.Spanned;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 二维码扫描Activity
 * @author yy-01
 *
 */
public class ScanCodeActivity extends BaseActivity {

	private TitlebarLayout titlebar;
	private RelativeLayout relativeLayout;
	private Context mContext;
	// 显示支付金额+
	private TextView mTvAmount;
	private TextView mTvDownTimer;
	private ImageView mIvPic;
	private BarcodeScanner scanner;
	private int mAmount ;
	private CloudPayApplication mApplication;
	private Integer mPaytype; // 支付类型
	private int mOpType;
	private static Integer SCAN_TIME = 60; // 扫描器运行时长（秒）
	private MyCountDownTimer mc;
	private IndicatorLight light;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_scancode);
		mContext = this;
		mApplication = (CloudPayApplication) getApplication();
		initView();
	}
	
	private void initView() {
		mTvAmount = (TextView) findViewById(R.id.tv_activity_scancode_amuont);
		mTvDownTimer = (TextView) findViewById(R.id.tv_activity_scancode_downtime);
		mIvPic = (ImageView) findViewById(R.id.iv_activity_scancode_pic);
		relativeLayout = (RelativeLayout) findViewById(R.id.titlebar_activity_scancode);
		Intent intent = getIntent();
		mOpType = intent.getIntExtra(Constant.PARAM_OPTYPE, Constant.KEYBOARD_OP_TYPE_PAY);
		mPaytype = intent.getIntExtra(Constant.PARAM_PAYTYPE, Constant.PAY_TYPE_ALIPAY);
		String title = "";
		if(mOpType == Constant.KEYBOARD_OP_TYPE_RETURN){
			title = "请使用二维码退款";
			mTvAmount.setText("扫描小票上的二维码退款");
			findViewById(R.id.tv_activity_scancode_description_1).setVisibility(View.INVISIBLE);
			findViewById(R.id.tv_activity_scancode_description_2).setVisibility(View.INVISIBLE);
		}else{
			mTvAmount.setText(getAmountText());
			title = "请使用二维码付款";
		}
		if(Constant.PAY_TYPE_MICROPAY.equals(mPaytype)){
			mIvPic.setImageResource(R.drawable.scanner_wx);
		}else if(Constant.PAY_TYPE_ALIPAY.equals(mPaytype)){
			mIvPic.setImageResource(R.drawable.scanner_alipay);
		}else if(Constant.PAY_TYPE_YIPAY.equals(mPaytype)){
			mIvPic.setImageResource(R.drawable.pp_16);
			mIvPic.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					openInput();
				}
			});
		}

		if("1".equals(mApplication.isMT())) {
			light = (IndicatorLight) mApplication.getDeviceInstance().getStandardModule(ModuleType.COMMON_INDICATOR_LIGHT);
		}

		titlebar = new TitlebarLayout(mContext, relativeLayout, title);
		titlebar.setTitlebarClickListener(new ITitlebarClickListener() {
			@Override
			public void OnRetrunListener(View view) {
				finish();
			}
		});
		mc = new MyCountDownTimer(SCAN_TIME*1000, 1000); 
	    mc.start();
	}

	private void openInput(){
		final ClearEditText et = new ClearEditText(this);
		new AlertDialog.Builder(this).setTitle("输入卡券编码")
				.setIcon(android.R.drawable.ic_dialog_info)
				.setView(et)
				.setPositiveButton("确定", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						String input = et.getText().toString();
						returnBack(RESULT_OK, input); // 扫描到的授权码
					}
				})
				.setNegativeButton("取消", null)
				.show();
	}
	/*
	 * 初始化扫描器
	 */
	private void initModule() {
		scanner = mApplication.getScanner();
		scanner.initScanner(this);
	}

	/*
	 * 运行扫描器
	 */
	private void runScanner() {
		light.turnOnLight(new LightType[]{LightType.GREEN_LIGHT});
		scanner.startScan(SCAN_TIME, TimeUnit.SECONDS, new ScannerListener() {
			@Override
			// 异步
			public void onResponse(String[] result) {
				mc.cancel(); // 定时器结束
				playBeepSoundAndVibrate(); // 播放音频
				stopScanner(); //调用停止扫描器方法
				returnBack(RESULT_OK, result[0]); // 扫描到的授权码
			}

			@Override
			public void onFinish() {
				stopScanner();
				light.turnOffLight(new LightType[]{LightType.GREEN_LIGHT});
			}
		});
	}
	
	/**
	 * 返回上一个页面
	 */
	private void returnBack(int resultCode, String scanCode) {
		Intent resultIntent = new Intent();
		resultIntent.putExtra(Constant.PARAM_SCANCODE, scanCode); 
		ScanCodeActivity.this.setResult(resultCode, resultIntent);
		finish();
	}

	/*
	 * 展示支付金额
	 */
	private Spanned getAmountText() {
		Intent intent = getIntent();
		String amountString = intent.getStringExtra(Constant.PARAM_AMOUNT);
		String summary = intent.getStringExtra(Constant.PARAM_SUMMARY);
		setmAmount(summary);
		String amount = "支付金额：" + amountString + "元";
		return Html.fromHtml(amount);
	}
	
	private MediaPlayer mediaPlayer;
	// 音量大小
	private static final float BEEP_VOLUME = 10.0f;
	// 震动时长
	private static final long VIBRATE_DURATION = 200L;
	// 是否震动
	private boolean vibrate = true;
	private boolean playBeep = true;

	/*
	 * 初始化音频
	 */
	private void initBeepSound() {
		AudioManager audioService = (AudioManager) getSystemService(AUDIO_SERVICE);
		if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
			playBeep = false;
		}
		if (mediaPlayer == null) {
			// The volume on STREAM_SYSTEM is not adjustable, and users found it
			// too loud,
			// so we now play on the music stream.
			setVolumeControlStream(AudioManager.STREAM_MUSIC);
			mediaPlayer = new MediaPlayer();
			mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
			// 使用系统铃声
			// mediaPlayer = MediaPlayer.create(this,
			// RingtoneManager.getActualDefaultRingtoneUri(this,
			// RingtoneManager.TYPE_NOTIFICATION));
			mediaPlayer.setOnCompletionListener(beepListener);
			mediaPlayer.setOnErrorListener(erroListener);
			AssetFileDescriptor file = getResources().openRawResourceFd(
					R.raw.beep);
			try {
				mediaPlayer.setDataSource(file.getFileDescriptor(),
						file.getStartOffset(), file.getLength());
				file.close();
				mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
				// //使用系统铃声，不再调用prepare（）方法
				mediaPlayer.prepare();
			} catch (Exception e) {
				mediaPlayer = null;
			}
		}
	}

	/*
	 * 播放音频
	 */
	private void playBeepSoundAndVibrate() {
		if (playBeep && mediaPlayer != null) {
			mediaPlayer.start();
		}
		if (vibrate) {
			Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
			vibrator.vibrate(VIBRATE_DURATION);
		}
	}

	/**
	 * When the beep has finished playing, rewind to queue up another one.
	 */
	private final OnCompletionListener beepListener = new OnCompletionListener() {
		public void onCompletion(MediaPlayer mediaPlayer) {
			mediaPlayer.seekTo(0);
			releaseMedia();
		}
	};

	private final OnErrorListener erroListener = new OnErrorListener() {
		@Override
		public boolean onError(MediaPlayer mp, int what, int extra) {
			releaseMedia();
			return false;
		}
	};

	
	public int getmAmount() {
		return mAmount;
	}

	public void setmAmount(String mAmount) {
		this.mAmount = Integer.parseInt(mAmount.trim());
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		if("1".equals(mApplication.isMT())){
			initModule();
			runScanner();
		}
		initBeepSound();
//		Log.d("ScanCode", "显示界面");
	}

	@Override
	protected void onPause() {
		super.onPause();
		if("1".equals(mApplication.isMT())){
			stopModule();
		}
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		if("1".equals(mApplication.isMT())) {
			light.turnOffLight(new LightType[]{LightType.GREEN_LIGHT});
		}
	}

	/**
	 * 停止扫描器
	 */
	private void stopScanner() {
		scanner.stopScan();
	}

	/*
	 * 释放硬件资源
	 */
	private void stopModule() {
		if (scanner != null) {
			stopScanner();
//			Log.e("TAG", "调用stopScanner方法");
		}
	}
	
	/*
	 * 释放音频资源
	 */
	private void releaseMedia() {
		if (mediaPlayer != null) {
			mediaPlayer.release();
			mediaPlayer = null;
//			Log.e("TAG", "释放音频资源");
		}
	}
	
	class MyCountDownTimer extends CountDownTimer { 
	    /** 
	     * @param millisInFuture 
	     *      表示以毫秒为单位 倒计时的总数 
	     *      例如 millisInFuture=1000 表示1秒 
	     * @param countDownInterval 
	     *      表示 间隔 多少微秒 调用一次 onTick 方法 
	     *      例如: countDownInterval =1000 ; 表示每1000毫秒调用一次onTick() 
	     */
	    public MyCountDownTimer(long millisInFuture, long countDownInterval) { 
	      super(millisInFuture, countDownInterval); 
	    } 
	  
	    @Override
	    public void onFinish() { 
	    	returnBack(RESULT_CANCELED, "");
	    } 
	  
	    @Override
	    public void onTick(long millisUntilFinished) { 
	    	mTvDownTimer.setText(String.format("%d", millisUntilFinished / 1000)); 
	    } 
	  } 
}
